package com.lzy.interceptor;

import com.lzy.token.TokenParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lzy by 2019/9/19 17:20
 */
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

    /**
     * swagger url
     */
    private final static String SWAGGER_URL = "v2/api-docs";

    private TokenParser tokenParser;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (isSwaggerUrl(request.getRequestURI().substring(1))) {
            return true;
        }
        if (!tokenParser.authorization(request, response)) {
            return Boolean.FALSE;
        }
        tokenParser.parserToken(request);
        return Boolean.TRUE;
    }

    /**
     * 是否swagger的url
     *
     * @param url swagger
     * @return
     */
    protected boolean isSwaggerUrl(String url) {
        return SWAGGER_URL.equals(url);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }

    public UserInfoInterceptor(TokenParser tokenParser) {
        this.tokenParser = tokenParser;
    }

    public UserInfoInterceptor() {
    }

}
